package operation

import (
	"../common"
	"../web"
	"encoding/json"
	"fmt"
	"strconv"
	"strings"
)

type OperPackingObj struct {
	common.BaseHandler
}

type OperForceCloseObj struct {
	common.BaseHandler
}

func (self *OperPackingObj) ParameterCheck() bool {
	s_ssns := strings.TrimSpace(self.Ctx.Params["ssn"])
	s_boxd := strings.TrimSpace(self.Ctx.Params["boxid"])
	s_bqty := strings.TrimSpace(self.Ctx.Params["baseqty"])
	s_line := self.Ctx.Params["line"]
	s_fcod := self.Ctx.Params["failcode"]

	err := ""
	status := common.GetScanStatus(self.Ctx, "WO PACKING")
	if !status {
		err = common.GetText(self.Lang, "System is busy, please wait a moment and try again.")
	}

	if s_ssns == "" {
		err = common.GetText(self.Lang, "Please input the Product No.")
	}

	if s_boxd == "" {
		packQty := *common.FetchOneRowPtr(
			`SELECT A.PRODTYPE, A.PACKQTY 
			   FROM SFC_ITEMS A(NOLOCK), SFC_SSN B(NOLOCK), SFC_WO C(NOLOCK)
			  WHERE B.SSN_NO=? 
			    AND B.WONO=C.WONO 
			    AND C.ITEM=A.ITEM`,
			self.Usr.Conn, new(common.NormalStruct), s_ssns)
		pt := strings.TrimSpace(packQty.(common.NormalStruct).Value1)
		qty := strings.TrimSpace(packQty.(common.NormalStruct).Value2)
		if pt == "A" && qty == "1" {
			s_boxd = s_ssns
			s_bqty = "1"
		} else if pt == "F" {
			s_boxd = ""
			s_bqty = qty
		} else {
			err = common.GetText(self.Lang, "Please input the BOX.")
		}
	}
	i_qty, errs := strconv.Atoi(s_bqty)
	if errs != nil {
		err = common.GetText(self.Lang, "BOX Qty must be a numeric.")
	}
	if i_qty < 1 {
		err = common.GetText(self.Lang, "Qty must be more than zero.")
	}
	if err != "" {
		iRtnData := *common.FetchOneRowPtr(
			`SELECT TOP 1 ISNULL(PACKEDQTY, 0) 
           	   FROM SFC_BOX(NOLOCK) 
          	  WHERE BOXID=?`,
			self.Usr.Conn, new(common.RecDataStr), s_boxd)
		packedqty := iRtnData.(common.RecDataStr).Data
		dict_js, _ := json.Marshal(map[string]string{"result": err, "packedqty": packedqty})
		self.Ctx.ResponseWriter.Write(dict_js)
		return false
	}

	self.Sqlparas = append(self.Sqlparas, s_boxd)
	self.Sqlparas = append(self.Sqlparas, i_qty)
	self.Sqlparas = append(self.Sqlparas, s_ssns)
	self.Sqlparas = append(self.Sqlparas, s_line)
	self.Sqlparas = append(self.Sqlparas, s_fcod)
	self.Sqlparas = append(self.Sqlparas, self.Usr.Username)

	return true
}

func (self *OperPackingObj) SqlQueryExecute() {
	s_boxd := self.Sqlparas[0].(string)
	s_ssns := self.Sqlparas[2].(string)
	common.SetScanStatus(self.Ctx, "WO PACKING", false)
	spRtnData := *common.FetchOneRowPtr(
		`sp_PackingDetail ?, ?, ?, ?, ?, ?`,
		self.Usr.Conn, new(common.SPReturn), self.Sqlparas...)
	common.SetScanStatus(self.Ctx, "WO PACKING", true)
	err := ""
	if spRtnData.(common.SPReturn).Flag > 0 || spRtnData.(common.SPReturn).EngMsg != "OK" {
		err = common.GetTextSP(self.Lang, spRtnData)
	}

	packedqty := "0"
	if self.TmplData["ProductionLine"] == "SFPRD06" {
		iRtnData := *common.FetchOneRowPtr(
			`SELECT TOP 1 A.PACKEDQTY 
		       FROM SFC_LARGEBOX A(NOLOCK), SFC_SSN B(NOLOCK) 
		  	  WHERE A.WORKORDER=B.WONO 
		    	AND B.SSN_NO=?`,
			self.Usr.Conn, new(common.RecDataStr), s_ssns)
		packedqty = iRtnData.(common.RecDataStr).Data
	} else {
		iRtnData := *common.FetchOneRowPtr(
			`SELECT TOP 1 ISNULL(PACKEDQTY, 0) 
           	   FROM SFC_BOX(NOLOCK) 
          	  WHERE BOXID=?`,
			self.Usr.Conn, new(common.RecDataStr), s_boxd)
		packedqty = iRtnData.(common.RecDataStr).Data
	}

	dict_js, _ := json.Marshal(map[string]string{"result": err, "packedqty": packedqty})
	self.Ctx.ResponseWriter.Write(dict_js)
}

func PackingScanHandler(ctx *web.Context) {
	self := new(OperPackingObj)
	self.Ctx = ctx
	self.DoJson(self)
}

func (self *OperForceCloseObj) ParameterCheck() bool {
	s_boxd := strings.TrimSpace(self.Ctx.Params["boxid"])

	err := ""

	if s_boxd == "" {
		err = common.GetText(self.Lang, "Please input the BOX.")
		dict_js, _ := json.Marshal(map[string]string{"result": err})
		self.Ctx.ResponseWriter.Write(dict_js)
		return false
	}

	self.Sqlparas = append(self.Sqlparas, s_boxd)
	self.Sqlparas = append(self.Sqlparas, self.Usr.Username)

	return true
}

func (self *OperForceCloseObj) SqlQueryExecute() {
	s_boxd := self.Sqlparas[0].(string)
	userid := self.Sqlparas[1].(string)
	err := ""
	iRtnData := *common.FetchOneRowPtr(
		`SELECT TOP 1 CLOSED 
	       FROM SFC_BOX(NOLOCK) 
	      WHERE BOXID=?`,
		self.Usr.Conn, new(common.RecDataStr), s_boxd)
	bclosed := iRtnData.(common.RecDataStr).Data
	if bclosed == "" {
		err = common.GetText(self.Lang, "BOXID is invalid.")
	}
	if bclosed == "1" {
		err = common.GetText(self.Lang, "The box has been closed.")
	}

	if err == "" {
		err := common.ExecSqlNonRst(
			`UPDATE SFC_BOX WITH(ROWLOCK) 
           		SET CLOSED=1,
           			FORCECLOSED=1,
           			MODIFYBY=?,
           			MODIFYDATE=GETDATE() 
         	  WHERE BOXID=?`,
			self.Usr.Conn, userid, s_boxd)
		if err != nil {
			common.Application.SendMail(fmt.Sprintf("Force Close Box [%s] Error: %v\n", s_boxd, err))
			return
		}
	}

	dict_js, _ := json.Marshal(map[string]string{"result": err})
	self.Ctx.ResponseWriter.Write(dict_js)
}

func ForceCloseScanHandler(ctx *web.Context) {
	self := new(OperForceCloseObj)
	self.Ctx = ctx
	self.DoJson(self)
}
